<template>
  <div>
    <van-nav-bar
      title="登录"
      left-text="返回"
      left-arrow
      @click-left="onClickLeft"
      @click-right="onClickRight"
      class="nav-box"
    />
    <van-form @submit="onSubmit" ref="formRef">
      <van-field
        v-model="mobile"
        name="mobile"
        left-icon="cashier-o"
        placeholder="请输入手机号"
        :rules="[{ required: true, message: '请填写手机号' }]"
      />
      <van-field
        v-model="code"
        type="password"
        name="code"
        left-icon="goods-collect-o"
        placeholder="请输入验证码"
        :rules="[{ required: true, message: '请填写验证码' }]"
      > <template #button>
        <!-- 倒计时组件 -->
      <van-count-down :time="1000 * 60" v-if="isCountDownShow" format="ss s" @finish="isCountDownShow = false"/>
      <van-button round  size="small" type="primary" @click="onSendSms" native-type="button">发送验证码</van-button>
    </template>
    </van-field>
      <div style="margin:36px 26px">
        <van-button  block type="info" native-type="submit"
          >登录</van-button
        >
      </div>
    </van-form>
  </div>
</template>

<script>
import { userLogin, getCode } from '@/api/user'
import { Toast } from 'vant'

export default {
  name: 'login-page',
  data () {
    return {
      // 1.表单数据：
      mobile: '',
      code: '',
      isCountDownShow: false // 是否展示倒计时
    }
  },
  // 方法：
  methods: {
    async onSubmit (values) {
      // debugger
      console.log('submit', values)
      // (1)发送注册请求：
      const res = await userLogin({
        mobile: '13911111111',
        code: '246810'
      })
      console.log(res)
      // (2)提示框：
      this.$toast.success('登录成功！')
      // (3)存储token:
      this.$store.commit('setUser', res.data)
      // (4)跳转首页：
      this.$router.push('/layout')
    },
    onClickLeft () {
      Toast('返回')
    },
    onClickRight () {
      Toast('按钮')
    },
    // 点击发送验证码
    async onSendSms () {
    //  1.验证手机号
      try {
        await this.$refs.formRef.validate('mobile')
        console.log('验证通过！')
      } catch (error) {
        return console.log('验证失败', error)
      }
      // 2.校验通过，显示倒计时
      this.isCountDownShow = true
      // 3.发送请求，获取验证码
      try {
        await getCode(this.mobile)
        this.$toast('发送成功！')
      } catch (error) {
        this.isCountDownShow = false
        if (error.response.status === 429) {
          this.$toast('当前发送太过频繁,请稍后重试！')
        } else {
          this.$toast('发送失败，请稍后重试！')
        }
      }
    }
  },
  // created钩子:
  created () {}
}
</script>

<style scoped lang="less">
.van-nav-bar{
   background-color: turquoise;
}
</style>
